//
/**
 * Filename: fig10-15_setsig.c
 * Author:   csbonkers
 * Contact:  forever65535@qq.com
 * Date:     2021/6/19
 * Description:
 *    信号设置和sigprocmask实例
 */

#include "apue.h"

static void sig_quit(int);

int main(int argc, char *argv[]) {
  sigset_t newmask, oldmask, pendmask;
  if (signal(SIGQUIT, sig_quit) == SIG_ERR) {
    err_sys("can't catch SIGQUIT");
  }
  //Block SIGQUIT and save current signal mask
  sigemptyset(&newmask);
  sigaddset(&newmask, SIGQUIT);
  if (sigprocmask(SIG_BLOCK, &newmask, &oldmask) < 0) {
    err_sys("SIG_BLOCK error");
  }
  sleep(30);// SIGQUIT here will remain pending
  if (sigpending(&pendmask) < 0) {
    err_sys("sigpending error");
  }
  if(sigismember(&pendmask, SIGQUIT)){
    printf("\nSIGQUIT pending\n");
  }
  // restore signal mask which unblock SIGQUIT
  if (sigprocmask(SIG_SETMASK, &oldmask, NULL) < 0) {
    err_sys("SIG_SETMASK error");
  }
  printf("SIGQUIT UNBLOCKED\n");
  sleep(30);// SIGQUIT here will terminate with core file
  return 0;
}

void sig_quit(int signo) {
  printf("caught SIGQUIT\n");
  if (signal(SIGQUIT, SIG_DFL) == SIG_ERR) {
    err_sys("can't reset SIGQUIT");
  }
}